import React, { useEffect, useState } from 'react';
import { Menu, Avatar, Dropdown } from 'antd';
import { UserOutlined, HomeOutlined, AppstoreOutlined, SettingOutlined } from '@ant-design/icons';
import config from '../config';
import './NavBar.css';
import { message } from 'antd';
import { useNavigate } from 'react-router-dom';
import { refreshToken } from '../api/user';

function getTokenRemaining() {
  const token = localStorage.getItem('token');
  if (!token) return null;
  try {
    const payload = JSON.parse(atob(token.split('.')[1]));
    if (!payload.exp) return null;
    const now = Math.floor(Date.now() / 1000);
    const remain = payload.exp - now;
    return remain > 0 ? remain : 0;
  } catch {
    return null;
  }
}

export default function NavBar({ user, onLogout }) {
  const navigate = useNavigate();
  const [remain, setRemain] = useState(getTokenRemaining());
  const [flashNew, setFlashNew] = useState(false);
  useEffect(() => {
    let refreshing = false;
    let refreshedThisCycle = false;
    const timer = setInterval(async () => {
      const remainNow = getTokenRemaining();
      setRemain(remainNow);
      // if (remainNow === 0) {
      //   message.error('登录已过期，请重新登录');
      //   setTimeout(() => {
      //     window.location.href = '/login';
      //   }, 1200);
      //   return;
      // }
      if (remainNow !== null && remainNow <= 30 && remainNow > 0 && !refreshing && !refreshedThisCycle) {
        refreshing = true;
        try {
          const data = await refreshToken();
          if (data && (data.token || (data.data && data.data.token))) {
            localStorage.setItem('token', data.token || data.data.token);
            setRemain(getTokenRemaining());
            refreshedThisCycle = true;
            setFlashNew(true);
            setTimeout(() => setFlashNew(false), 2000);
          }
        } catch {}
        setTimeout(() => { refreshing = false; }, 2000);
      }
      // 如果token剩余时间大于30秒，允许下次周期性刷新
      if (remainNow > 30) {
        refreshedThisCycle = false;
      }
    }, 1000);
    return () => clearInterval(timer);
  }, []);
  const handleMenuClick = ({ key }) => {
    if (key === 'profile') {
      if (user && user.username) {
        navigate('/profile');
      } else {
        message.warning('请先登录');
        navigate('/login');
      }
    } else if (key === 'logout') {
      if (onLogout) onLogout();
    }
  };
  const menuItems = [
    { key: 'profile', icon: <UserOutlined />, label: '个人中心' },
    { key: 'logout', icon: <SettingOutlined />, label: '退出登录' },
  ];
  return (
    <div className="navbar-root">
      <div className="navbar-left">
        <img src={config.LOGO_URL} alt="logo" className="navbar-logo" />
        <span className="navbar-title">{config.PROJECT_NAME}</span>
      </div>
      <div className="navbar-right">
        <Dropdown menu={{ items: menuItems, onClick: handleMenuClick }} placement="bottomRight">
          <div className="navbar-user">
            {remain !== null && (
              <span style={{
                color: flashNew ? '#52c41a' : remain < 30 ? 'orange' : '#888',
                marginRight: 12,
                fontWeight: 500,
                transition: 'color 0.3s',
              }}>
                {remain > 0
                  ? (flashNew
                      ? `新Token剩余${Math.floor(remain/60)}:${String(remain%60).padStart(2,'0')}`
                      : remain < 30
                        ? `Token即将过期(${Math.floor(remain/60)}:${String(remain%60).padStart(2,'0')})`
                        : `Token剩余${Math.floor(remain/60)}:${String(remain%60).padStart(2,'0')}`)
                  : 'Token已过期'}
              </span>
            )}
            <Avatar src={user?.avatar} icon={<UserOutlined />} />
            <span className="navbar-username">{user?.username || '未登录'}</span>
          </div>
        </Dropdown>
      </div>
    </div>
  );
} 